<template>
    <div class="daily-challenges-page">
        <!-- 导航栏 -->
        <van-nav-bar title="Daily Challenges" left-arrow @click-left="goBack" fixed>
            <template #right>
                <van-icon name="question-o" @click="showChallengeInfo" />
            </template>
        </van-nav-bar>

        <!-- 挑战概览 -->
        <div class="challenges-overview">
            <div class="streak-section">
                <div class="streak-card">
                    <div class="streak-icon">
                        <van-icon name="fire-o" />
                    </div>
                    <div class="streak-info">
                        <div class="streak-number">{{ currentStreak }}</div>
                        <div class="streak-label">Day Streak</div>
                    </div>
                </div>
                <div class="streak-calendar">
                    <div v-for="(day, index) in streakDays" :key="index" class="streak-day"
                        :class="{ completed: day.completed, today: day.isToday }">
                        <van-icon v-if="day.completed" name="success" />
                        <span v-else>{{ day.day }}</span>
                    </div>
                </div>
            </div>

            <!-- 今日进度 -->
            <div class="daily-progress">
                <div class="progress-header">
                    <h3>Today's Progress</h3>
                    <span class="progress-text">{{ completedChallenges }}/{{ totalChallenges }} completed</span>
                </div>
                <van-progress :percentage="(completedChallenges / totalChallenges) * 100" stroke-width="8"
                    color="#07c160" track-color="#f5f5f5" />
                <div class="progress-rewards">
                    <div class="reward-item">
                        <van-icon name="diamond-o" />
                        <span>+{{ dailyPoints }} points</span>
                    </div>
                    <div class="reward-item">
                        <van-icon name="trophy-o" />
                        <span>Streak bonus</span>
                    </div>
                </div>
            </div>
        </div>

        <!-- 挑战分类 -->
        <div class="challenge-categories">
            <van-tabs v-model:active="activeCategory" @change="handleCategoryChange">
                <van-tab title="All" name="all" />
                <van-tab title="Training" name="training" />
                <van-tab title="Community" name="community" />
                <van-tab title="Learning" name="learning" />
            </van-tabs>
        </div>

        <!-- 挑战列表 -->
        <div class="challenges-content">
            <van-loading v-if="loading" size="24px" vertical>Loading challenges...</van-loading>
            <div v-else-if="filteredChallenges.length > 0" class="challenges-list">
                <ChallengeCard v-for="challenge in filteredChallenges" :key="challenge.id" :challenge="challenge"
                    @start="startChallenge" @complete="completeChallenge" @claim="claimReward" />
            </div>
            <van-empty v-else description="No challenges available" image="search">
                <van-button type="primary" @click="refreshChallenges">
                    Refresh Challenges
                </van-button>
            </van-empty>
        </div>

        <!-- 挑战历史 -->
        <div class="challenge-history">
            <div class="history-header">
                <h3>Recent Achievements</h3>
                <van-button size="mini" @click="viewAllHistory">View All</van-button>
            </div>
            <div class="history-list">
                <div v-for="achievement in recentAchievements" :key="achievement.id" class="history-item">
                    <div class="achievement-icon">
                        <van-icon :name="achievement.icon" />
                    </div>
                    <div class="achievement-info">
                        <div class="achievement-title">{{ achievement.title }}</div>
                        <div class="achievement-time">{{ formatTime(achievement.completed_at) }}</div>
                    </div>
                    <div class="achievement-reward">
                        <span>+{{ achievement.points }}</span>
                    </div>
                </div>
            </div>
        </div>

        <!-- 信息弹窗 -->
        <van-popup v-model:show="showInfoPopup" position="bottom" :style="{ height: '60%' }" round>
            <div class="info-modal">
                <div class="info-header">
                    <h3>About Daily Challenges</h3>
                    <van-icon name="cross" @click="showInfoPopup = false" />
                </div>
                <div class="info-content">
                    <div class="info-section">
                        <h4>How It Works</h4>
                        <p>Complete daily challenges to earn points, maintain your streak, and unlock special rewards.
                            New
                            challenges are available every day!</p>
                    </div>
                    <div class="info-section">
                        <h4>Streak Rewards</h4>
                        <div class="streak-rewards">
                            <div class="reward-tier">
                                <span class="tier-days">7 days</span>
                                <span class="tier-reward">+50 bonus points</span>
                            </div>
                            <div class="reward-tier">
                                <span class="tier-days">14 days</span>
                                <span class="tier-reward">Special badge</span>
                            </div>
                            <div class="reward-tier">
                                <span class="tier-days">30 days</span>
                                <span class="tier-reward">Exclusive achievement</span>
                            </div>
                        </div>
                    </div>
                    <div class="info-section">
                        <h4>Challenge Types</h4>
                        <div class="challenge-types">
                            <div class="type-item">
                                <van-icon name="play-circle-o" />
                                <span>Training Sessions</span>
                            </div>
                            <div class="type-item">
                                <van-icon name="friends-o" />
                                <span>Community Interaction</span>
                            </div>
                            <div class="type-item">
                                <van-icon name="star-o" />
                                <span>Skill Practice</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </van-popup>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
// import { motivationApi } from '@/api' // 暂时注释掉，实际项目中会用到
import type { DailyChallenge } from '@/api/dailyChallenge'
import ChallengeCard from '@/components/ChallengeCard.vue'

const router = useRouter()

// 响应式数据
const loading = ref(true)
const activeCategory = ref('all')
const challenges = ref<DailyChallenge[]>([])
const currentStreak = ref(7)
const showInfoPopup = ref(false)

// 连续签到天数数据
const streakDays = ref([
    { day: 'M', completed: true, isToday: false },
    { day: 'T', completed: true, isToday: false },
    { day: 'W', completed: true, isToday: false },
    { day: 'T', completed: true, isToday: false },
    { day: 'F', completed: true, isToday: false },
    { day: 'S', completed: true, isToday: false },
    { day: 'S', completed: false, isToday: true }
])

// 最近成就数据
const recentAchievements = ref([
    {
        id: 1,
        title: 'Communication Practice',
        icon: 'chat-o',
        points: 50,
        completed_at: '2024-10-22T09:30:00Z'
    },
    {
        id: 2,
        title: 'Community Helper',
        icon: 'friends-o',
        points: 75,
        completed_at: '2024-10-21T16:45:00Z'
    },
    {
        id: 3,
        title: 'Skill Builder',
        icon: 'star-o',
        points: 100,
        completed_at: '2024-10-21T14:20:00Z'
    }
])

// 模拟挑战数据
const initializeMockData = () => {
    challenges.value = [
        {
            id: 1,
            title: 'Morning Training',
            description: 'Complete a 15-minute communication training session',
            category: 'training',
            difficulty: 'easy',
            points: 50,
            time_limit: 900, // 15 minutes in seconds
            is_completed: false,
            is_claimed: false,
            progress: {
                current: 0,
                target: 1
            },
            requirements: ['Complete any training scenario'],
            icon: 'play-circle-o',
            expires_at: '2024-10-22T23:59:59Z'
        },
        {
            id: 2,
            title: 'Community Engagement',
            description: 'Like and comment on 3 community posts',
            category: 'community',
            difficulty: 'easy',
            points: 30,
            is_completed: true,
            is_claimed: false,
            progress: {
                current: 3,
                target: 3
            },
            requirements: ['Like 3 posts', 'Comment on 3 posts'],
            icon: 'friends-o',
            expires_at: '2024-10-22T23:59:59Z'
        },
        {
            id: 3,
            title: 'Skill Mastery',
            description: 'Achieve a score of 8+ in any negotiation scenario',
            category: 'training',
            difficulty: 'medium',
            points: 100,
            is_completed: false,
            is_claimed: false,
            progress: {
                current: 0,
                target: 1
            },
            requirements: ['Score 8+ in negotiation scenario'],
            icon: 'trophy-o',
            expires_at: '2024-10-22T23:59:59Z'
        },
        {
            id: 4,
            title: 'Knowledge Seeker',
            description: 'Read 5 articles in the learning center',
            category: 'learning',
            difficulty: 'easy',
            points: 40,
            is_completed: false,
            is_claimed: false,
            progress: {
                current: 2,
                target: 5
            },
            requirements: ['Read 5 articles'],
            icon: 'book-o',
            expires_at: '2024-10-22T23:59:59Z'
        },
        {
            id: 5,
            title: 'Mentor Mode',
            description: 'Help 2 community members with their questions',
            category: 'community',
            difficulty: 'medium',
            points: 80,
            is_completed: false,
            is_claimed: false,
            progress: {
                current: 0,
                target: 2
            },
            requirements: ['Answer 2 help requests'],
            icon: 'manager-o',
            expires_at: '2024-10-22T23:59:59Z'
        },
        {
            id: 6,
            title: 'Perfect Practice',
            description: 'Complete 3 training sessions without mistakes',
            category: 'training',
            difficulty: 'hard',
            points: 150,
            is_completed: false,
            is_claimed: false,
            progress: {
                current: 1,
                target: 3
            },
            requirements: ['Complete 3 perfect sessions'],
            icon: 'star-o',
            expires_at: '2024-10-22T23:59:59Z'
        }
    ] as DailyChallenge[]
}

// 计算属性
const completedChallenges = computed(() => {
    return challenges.value.filter(c => c.is_completed).length
})

const totalChallenges = computed(() => {
    return challenges.value.length
})

const dailyPoints = computed(() => {
    return challenges.value
        .filter(c => c.is_completed)
        .reduce((sum, c) => sum + c.points, 0)
})

const filteredChallenges = computed(() => {
    if (activeCategory.value === 'all') {
        return challenges.value
    }
    return challenges.value.filter(c => c.category === activeCategory.value)
})

// 方法
const loadChallenges = async () => {
    try {
        loading.value = true
        // const response = await motivationApi.getDailyChallenges()
        // challenges.value = response.data

        // 模拟API延迟
        await new Promise(resolve => setTimeout(resolve, 500))
    } catch (error) {
        console.error('Failed to load challenges:', error)
        showToast('Failed to load challenges')
    } finally {
        loading.value = false
    }
}

const handleCategoryChange = (name: string) => {
    // 筛选逻辑已在计算属性中处理
}

const startChallenge = (challenge: DailyChallenge) => {
    showToast(`Starting ${challenge.title}...`)

    // 根据挑战类型跳转到相应页面
    switch (challenge.category) {
        case 'training':
            router.push('/training')
            break
        case 'community':
            router.push('/community')
            break
        case 'learning':
            router.push('/learning')
            break
        default:
            showToast('Challenge started!')
    }
}

const completeChallenge = async (challenge: DailyChallenge) => {
    try {
        // await motivationApi.completeChallenge(challenge.id)

        challenge.is_completed = true
        challenge.progress!.current = challenge.progress!.target

        showToast(`Challenge completed! +${challenge.points} points`)
    } catch (error) {
        console.error('Failed to complete challenge:', error)
        showToast('Failed to complete challenge')
    }
}

const claimReward = async (challenge: DailyChallenge) => {
    try {
        // await motivationApi.claimChallengeReward(challenge.id)

        challenge.is_claimed = true
        showToast(`Reward claimed! +${challenge.points} points`)
    } catch (error) {
        console.error('Failed to claim reward:', error)
        showToast('Failed to claim reward')
    }
}

const refreshChallenges = () => {
    loadChallenges()
}

const viewAllHistory = () => {
    showToast('Viewing challenge history...')
}

const showChallengeInfo = () => {
    showInfoPopup.value = true
}

const formatTime = (timestamp: string) => {
    const now = new Date()
    const time = new Date(timestamp)
    const diffInHours = Math.floor((now.getTime() - time.getTime()) / (1000 * 60 * 60))

    if (diffInHours < 1) {
        return 'Just now'
    } else if (diffInHours < 24) {
        return `${diffInHours}h ago`
    } else {
        const days = Math.floor(diffInHours / 24)
        return `${days}d ago`
    }
}

const goBack = () => {
    router.back()
}

// 生命周期
onMounted(() => {
    initializeMockData()
    loadChallenges()
})
</script>

<style lang="scss" scoped>
.daily-challenges-page {
    min-height: 100vh;
    background: #f7f8fa;
    padding-top: 46px;

    .challenges-overview {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        padding: 24px 20px;

        .streak-section {
            margin-bottom: 24px;

            .streak-card {
                display: flex;
                align-items: center;
                gap: 12px;
                margin-bottom: 16px;

                .streak-icon {
                    .van-icon {
                        font-size: 32px;
                        color: #ffd21e;
                    }
                }

                .streak-info {
                    .streak-number {
                        font-size: 28px;
                        font-weight: 700;
                        line-height: 1;
                    }

                    .streak-label {
                        font-size: 14px;
                        opacity: 0.8;
                    }
                }
            }

            .streak-calendar {
                display: flex;
                justify-content: space-between;
                gap: 4px;

                .streak-day {
                    width: 36px;
                    height: 36px;
                    border-radius: 8px;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    font-size: 12px;
                    font-weight: 500;
                    background: rgba(255, 255, 255, 0.2);

                    &.completed {
                        background: #07c160;
                        color: white;

                        .van-icon {
                            font-size: 16px;
                        }
                    }

                    &.today {
                        background: #ffd21e;
                        color: #323233;
                    }
                }
            }
        }

        .daily-progress {
            .progress-header {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin-bottom: 12px;

                h3 {
                    font-size: 16px;
                    font-weight: 600;
                    margin: 0;
                }

                .progress-text {
                    font-size: 14px;
                    opacity: 0.9;
                }
            }

            .progress-rewards {
                display: flex;
                justify-content: center;
                gap: 20px;
                margin-top: 12px;

                .reward-item {
                    display: flex;
                    align-items: center;
                    gap: 6px;
                    font-size: 13px;

                    .van-icon {
                        color: #ffd21e;
                        font-size: 16px;
                    }
                }
            }
        }
    }

    .challenge-categories {
        background: white;
        border-bottom: 1px solid #ebedf0;
    }

    .challenges-content {
        padding: 20px;

        .challenges-list {
            display: flex;
            flex-direction: column;
            gap: 16px;
        }
    }

    .challenge-history {
        background: white;
        margin: 20px;
        border-radius: 12px;
        padding: 20px;

        .history-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 16px;

            h3 {
                font-size: 16px;
                font-weight: 600;
                color: #323233;
                margin: 0;
            }
        }

        .history-list {
            .history-item {
                display: flex;
                align-items: center;
                padding: 12px 0;
                border-bottom: 1px solid #f5f5f5;

                &:last-child {
                    border-bottom: none;
                }

                .achievement-icon {
                    width: 40px;
                    height: 40px;
                    background: #f0f8ff;
                    border-radius: 8px;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    margin-right: 12px;

                    .van-icon {
                        color: #1989fa;
                        font-size: 18px;
                    }
                }

                .achievement-info {
                    flex: 1;

                    .achievement-title {
                        font-size: 14px;
                        font-weight: 500;
                        color: #323233;
                        margin-bottom: 2px;
                    }

                    .achievement-time {
                        font-size: 12px;
                        color: #969799;
                    }
                }

                .achievement-reward {
                    font-size: 14px;
                    font-weight: 600;
                    color: #07c160;
                }
            }
        }
    }

    .info-modal {
        height: 100%;
        display: flex;
        flex-direction: column;

        .info-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 20px;
            border-bottom: 1px solid #ebedf0;

            h3 {
                font-size: 18px;
                font-weight: 600;
                color: #323233;
                margin: 0;
            }

            .van-icon {
                color: #969799;
                cursor: pointer;
            }
        }

        .info-content {
            flex: 1;
            padding: 20px;
            overflow-y: auto;

            .info-section {
                margin-bottom: 24px;

                h4 {
                    font-size: 16px;
                    font-weight: 600;
                    color: #323233;
                    margin: 0 0 8px 0;
                }

                p {
                    font-size: 14px;
                    color: #646566;
                    line-height: 1.5;
                    margin: 0;
                }

                .streak-rewards {
                    .reward-tier {
                        display: flex;
                        justify-content: space-between;
                        align-items: center;
                        padding: 8px 12px;
                        background: #f7f8fa;
                        border-radius: 6px;
                        margin-bottom: 8px;

                        .tier-days {
                            font-size: 14px;
                            font-weight: 500;
                            color: #323233;
                        }

                        .tier-reward {
                            font-size: 13px;
                            color: #1989fa;
                        }
                    }
                }

                .challenge-types {
                    display: flex;
                    flex-direction: column;
                    gap: 8px;

                    .type-item {
                        display: flex;
                        align-items: center;
                        gap: 8px;
                        padding: 8px;
                        background: #f7f8fa;
                        border-radius: 6px;

                        .van-icon {
                            color: #1989fa;
                            font-size: 16px;
                        }

                        span {
                            font-size: 13px;
                            color: #323233;
                        }
                    }
                }
            }
        }
    }
}
</style>